#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <cerrno>
#include <cstring>
using namespace std;

void SetNonBlock(int fd)
{
    int flags = fcntl(fd, F_GETFL); // 获取标记位
    if (flags < 0)
    { // 获取标记位失败
        perror("fcntl");
        return;
    }
    fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}

int main()
{
    char buff[1024];

    SetNonBlock(0);

    while (true)
    {
        printf("Please Enter # ");
        fflush(stdout);
        ssize_t n = read(0, buff, sizeof(buff) - 1);

        if (n > 0)
        {
            buff[n - 1] = 0;
            cout << "Echo: " << buff << endl;
        }
        else if (0 == n)
        {
            cout << "Read Done" << endl;

            break;
        }        else
        {
            if (errno == EWOULDBLOCK)
            {
                cout << "Resource temporarily unavailable" << endl;
                // TODO
            }
            else
            {
                cout << "Read Error , n = " << n << " errno code: " << errno << "  " << strerror(errno) << endl;
            }
        }
        sleep(1);
    }

    return 0;
}



